package com.ipad.ui.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.cooltechworks.views.shimmer.ShimmerRecyclerView;
import com.ipad.R;
import com.ipad.bean.Warehouse;
import com.ipad.net.entity.DeliveryContainerEntity;
import com.ipad.net.entity.DeliveryCount;
import com.ipad.net.entity.DeliveryListEntity;
import com.ipad.net.entity.DeliveryListInfoEntity;
import com.ipad.net.entity.LoginEntity;
import com.ipad.net.entity.UserInfo;
import com.ipad.net.entity.WarehouseList;
import com.ipad.net.presenter.StroePresenter;
import com.ipad.net.presenter.UserPresent;
import com.ipad.net.view.IStoreView;
import com.ipad.net.view.IUserView;
import com.ipad.ui.BaseActivity;
import com.ipad.ui.adapter.TestAdapter;
import com.ipad.ui.fragmen.WarehousV2Fragment;
import com.ipad.utils.ActivityStack;
import com.ipad.utils.SharePerenceUtils;
import com.ipad.utils.ToasUtils;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.greenrobot.greendao.annotation.Index;

import java.util.List;

import butterknife.BindView;
import pub.devrel.easypermissions.EasyPermissions;

public class IndexActivity extends BaseActivity implements IUserView ,WarehousV2Fragment.OnSelectWarehouse, IStoreView,EasyPermissions.PermissionCallbacks {
    @BindView(R.id.generation_distribution_number)
    TextView generation_distribution_number;
    @BindView(R.id.total_deliveries_this_week)
    TextView total_deliveries_this_week;
    @BindView(R.id.total_deliveries_this_month)
    TextView total_deliveries_this_month;
    @BindView(R.id.index_warehouse)
    TextView index_warehouse;
    @BindView(R.id.index_user)
    TextView index_user;
    @BindView(R.id.exit)
    TextView exit;
    @BindView(R.id.index_distribution)
    RadioButton index_distribution;
    @BindView(R.id.index_delivery_history)
    RadioButton index_delivery_history;
    @BindView(R.id.user_info_linear)
    LinearLayout user_info_linear;

    UserPresent userPresent;
    StroePresenter stroePresenter;
    String token;
    private String TAG = "index";
    private boolean isFirst = true;
    private long first_time = 0L;

    @Override
    public int getLayoutId() {
        return R.layout.activity_index;
    }

    @Override
    public void initView() {
        if (toMainActivity()){
            return;
        }

        userPresent = new UserPresent();
        userPresent.attchView(this);
        stroePresenter = new StroePresenter();
        stroePresenter.attchView(this);
        stroePresenter.getDeliveryCount(SharePerenceUtils.getToken(this),false  );
//        String uid = SharePerenceUtils.getStringValue(SharePerenceUtils.getInstance(this, SharePerenceUtils.user_title), SharePerenceUtils.user_id);
//        if (uid != null && !uid.equals("")) {
//            getUserList();
//        } else {
        getInfo();
//        }
        if (SharePerenceUtils.getWarehouseId(this) == null || SharePerenceUtils.getWarehouseId(this).equals("")) {
            getWarehouse();
        } else {
            index_warehouse.setText(SharePerenceUtils.getWarehouseName(this));
        }
        //退出
        exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharePerenceUtils.clear(IndexActivity.this, SharePerenceUtils.user_title);
                Intent intent = new Intent(IndexActivity.this, LoginActivity.class);
                startActivity(intent);
                ActivityStack.getInstance().removeAllActivityExcept(LoginActivity.class);
            }
        });
        //选择库房
        user_info_linear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WarehousV2Fragment warehousV2Fragment = WarehousV2Fragment.newInstance(2);
                warehousV2Fragment.show(getSupportFragmentManager(), "");
            }
        });
        final String[] perms = {Manifest.permission.CAMERA};
        //功能
        index_distribution.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(IndexActivity.this,DeliveryActivity.class);
                overridePendingTransition(0,0);
                startActivity(intent);
//                boolean b = hasPresmisson(perms);
//                Log.e(TAG, "onClick: "+b );
//                if (b){
//                    Intent intent = new Intent(IndexActivity.this, ResultActivity.class);
//                    startActivityForResult(intent, 0x11);
//                }else {
//                    EasyPermissions.requestPermissions(IndexActivity.this,IndexActivity.this.getString(R.string.add_permission),0x11,perms);
//                }


            }
        });
        index_delivery_history.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(IndexActivity.this,DeliveryRecordActivity.class);
                overridePendingTransition(0,0);
                startActivity(intent);
            }
        });
    }

    @Override
    public void initData() {


    }

    @Override
    public void setToolbar() {

    }

    public void getInfo() {
        if (userPresent != null) {
            userPresent.getUserInfo(SharePerenceUtils.getToken(this));
        }
    }

    public void getWarehouse() {
        if (userPresent != null) {
            userPresent.getWarehouseList("1",SharePerenceUtils.getToken(this), "1", "5", "", false);
        }
    }

    public boolean toMainActivity() {
        token = SharePerenceUtils.getToken(this);

        if (token == null || token.equals("")) {
            Intent intent = new Intent(IndexActivity.this, LoginActivity.class);
            overridePendingTransition(0, 0);
            startActivity(intent);
            finish();
            return true;
        }
        return false;
    }


    @Override
    public void stopLoading() {
        super.dismissDialog();
    }

    @Override
    public void loading(String msg) {
        loadingDialog.setInf(msg);
        super.showDialog(msg);
    }

    @Override
    public void error(String msg) {
        ToasUtils.getToast(msg, this);
    }

    @Override
    public void getUserInfo(UserInfo user) {

        if (user != null) {
            if (user.getCode().equals("200")) {
                SharePerenceUtils.setUser(this, user.getUser());
                index_user.setText(user.getUser().getUsername());
            }
            if (user.getCode().equals("401")) {
                ToasUtils.getToast(user.getMessage(), this);
//                SharePerenceUtils.clear(OperationMainActivity.this, SharePerenceUtils.user_title);
                Intent intent = new Intent(IndexActivity.this, LoginActivity.class);
                startActivity(intent);
                ActivityStack.getInstance().removeAllActivityExcept(LoginActivity.class);
            }
        } else {
            getUserError();
        }
    }

    @Override
    public void getUserError() {
        AlertDialog alertDialog = new AlertDialog.Builder(this)
                .setNegativeButton("重新获取", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getInfo();

                    }

                })
                .setPositiveButton("重新登录", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                        SharePerenceUtils.clear(OperationMainActivity.this, SharePerenceUtils.user_title);
                        Intent intent = new Intent(IndexActivity.this, LoginActivity.class);
                        startActivity(intent);
                        ActivityStack.getInstance().removeAllActivityExcept(LoginActivity.class);

                    }
                })
                .setMessage("获取用户信息失败，是否重新加载?")
                .create();
        alertDialog.setCancelable(false);
        alertDialog.show();
    }

    @Override
    public void login(LoginEntity loginEntity) {

    }

    @Override
    public void getWarehouseList(WarehouseList warehouseList) {
        if (warehouseList != null) {
            if (warehouseList.getList() != null && warehouseList.getList().size() != 0) {
                SharePerenceUtils.setWarehouse(this, warehouseList.getList().get(0));
                index_warehouse.setText(warehouseList.getList().get(0).getName());
            }
        }
    }

    @Override
    public void onBackPressed() {
        long l = System.currentTimeMillis();
        if (isFirst) {
            isFirst = false;
            ToasUtils.showToast(this, "再次点击退出");
            first_time = System.currentTimeMillis();
        } else {
            if (l - first_time <= 2000) {
                super.onBackPressed();
                ActivityStack.getInstance().removeAllActivityExcept();
            } else {
                isFirst = true;
                ToasUtils.showToast(this, "再次点击退出");


            }

        }

    }


    public void getUserList() {
        SharedPreferences instance = SharePerenceUtils.getInstance(this, SharePerenceUtils.user_title);
        String name = instance.getString(SharePerenceUtils.user_name, "");

    }

    @Override
    public void selectWarehouse(Warehouse warehouse) {
        SharePerenceUtils.setWarehouse(this, warehouse);
        index_warehouse.setText(warehouse.getName());
    }

    @Override
    public void getDeliveryListSuccess(DeliveryListEntity deliveryListEntity) {

    }

    @Override
    public void getDeliveryDetailSuccess(DeliveryListInfoEntity deliveryListInfoEntity) {

    }

    @Override
    public void getDeliveryCountSuccess(DeliveryCount count) {
        if (count!=null){
            if (count.getCode() == 200){
                generation_distribution_number.setText(count.getData().getWaiteCount().toString());
                total_deliveries_this_week.setText(count.getData().getWeekCount().toString());
                total_deliveries_this_month.setText(count.getData().getMonthCount().toString());
            }
        }
    }

    @Override
    public void getDeliveryByContainerSuccess(DeliveryContainerEntity count) {

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x11) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    Intent intent = new Intent(IndexActivity.this, DeliveryContainerActivity.class);
                    intent.putExtra("result",result);
                    overridePendingTransition(0, 0);
                    startActivity(intent);

                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(this, "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode,permissions,grantResults,this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        ToasUtils.getToast("请在设置中添加\"相机\"权限",this);
    }
}
